const News = require('../models/News');
const {uploadURL, uploadPath} = require("../config");
const fs = require("fs");
const path = require("path");


// 新闻列表
exports.getNews = async function (req, res, next) {
  const pageNumber = req.query.pageNumber ? parseInt(req.query.pageNumber) : 1
  const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 3
  const filter = {}
  if (req.query.title) {
    filter.title = {$regex: req.query.title}
  }
  if (req.query.content) {
    filter.content = {$regex: req.query.content}
  }
  try {
    let total = await News.find(filter).count()
    let result = await News.find(filter).sort({'updatedAt': -1}).skip((pageNumber - 1) * pageSize).limit(pageSize).populate({
      "path": 'author',
      "select": " username"
    }).exec()
    console.log("-> result", result);
    result = result.map(item => {
      return {
        _id: item._id,
        title: item.title,
        cover: uploadURL + item.cover,
        username:item.author.username,
        updatedAt: item.updatedAt
      }
    })
    res.json({
      code: 20000,
      data: result,
      pagination: {
        total,
        pageSize,
        pageNumber
      }
    })
  } catch (err) {
    next(err)
  }
}

//单条新闻
exports.getOneNews = async function (req, res, next) {
  const _id = req.params.id
  try {
    let result = await News.findById(_id).select("title cover content updatedAt");
    console.log("-> result:",result);
    result ={
      _id: result._id,
      title: result.title,
      cover: uploadURL + result.cover,
      content:result.content,
      updatedAt: result.updatedAt
    }

    res.json({
      code: 20000,
      data: result
    })
  } catch (err) {
    next(err)
  }
}

//修改新闻
exports.updateNews = async (req, res, next) => {
  const _id = req.params.id
  let body = req.body
  if (body.cover) {
    body.cover = body.cover.replace(uploadURL, '')
  }
  try {
    let oldResult = await News.findById(_id)
    let imgPath = path.join(uploadPath, `/${oldResult.cover}`)
    // 如果图片存在并且图片不是同一张，删除本地图片文件
    if (fs.existsSync(imgPath) && oldResult.cover !== body.cover) {
      fs.unlinkSync(imgPath)
    }
    await News.findByIdAndUpdate(_id, body)
    res.json({
      code: 20000,
      message: '更新成功'
    })
  } catch (err) {
    next(err)
  }
}
//先上传图片,最后提交
exports.addNews = async function (req, res, next) {
  let body = req.body
  if (body.cover) {
    body.cover = body.cover.replace(uploadURL, '')
  }
  try {
    const result = await News.create({
      ...body,
      author: req._id
    })
    res.json({
      code: 20000,
      message: '新闻提交成功',
      data: {
        id: result._id
      }
    })
  } catch (err) {
    next(err)
  }
}
//提交新闻后端处理图片然后提交
exports.addNews2 = async function (req, res, next) {
  try {
    const {title, content} = req.body
    const result = await News.create({
      title,
      content,
      cover: req.imgUrl,
      author: req._id
    })
    res.json({
      code: 20000,
      message: '提交成功',
      data: {
        id: result._id
      }
    })
  } catch (err) {
    next(err)
  }
}
//删除单条新闻
exports.delNews = async (req, res, next) => {
  const _id = req.params.id
  try {
    let result = await News.findByIdAndDelete(_id)
    let imgPath = path.join(uploadPath, `/${result.cover}`)
    // 如果存在，删除本地图片文件
    if (fs.existsSync(imgPath)) {
      fs.unlinkSync(imgPath)
    }
    res.json({
      code: 20000,
      message: '删除新闻成功'
    })
  } catch (err) {
    next(err)
  }
}
